package com.lfc.myframe.utils.download;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RemoteViews;
import android.widget.TextView;

import androidx.core.app.NotificationCompat;
import androidx.core.content.FileProvider;

import com.lfc.DuLaiDuWang.utils.download.DownloadAPi;
import com.lfc.myframe.R;
import com.lfc.myframe.utils.FileUtil;
import com.lfc.myframe.widget.numsprogress.NumberProgressBar;

import java.io.File;
import java.text.DecimalFormat;

import static com.lfc.myframe.share.Const.Data_FileDirPath;


/**
 * 优化 下载类 下个项目使用
 */


public class DownLoadUtil {

    private static final String TAG = "DownLoadUtil";
    private Activity activity;
    private String mDownloadFileName;
    private String downloadUrl;
    private boolean force = false;
    private boolean is_bg = false; // 是否后台下载
    /*是否正在下载*/
    private boolean isLoading = false;
    private NotificationManager mNotifyManager;
    private Notification mNotification;

    private Handler handler = new Handler();

    private int downloadId = 0;

    private AlertDialog dialog;
    private NumberProgressBar pb;

    public boolean isLoading() {
        return isLoading;
    }

    public void setLoading(boolean loading) {
        isLoading = loading;
    }

    public DownLoadUtil(Activity activity, String mDownloadFileName, String downloadUrl, boolean force) {
        this.activity = activity;
        this.mDownloadFileName = mDownloadFileName;
        this.downloadUrl = downloadUrl;
        this.force = force;
    }

    public void start() {
        if (isLoading) return;
        isLoading = true;
        final File file1 = new File(Data_FileDirPath);
//        final File file = FileUtil.createFile(mDownloadFileName);
        // 判断文件目录是否存在
        if (!file1.exists()) {
            file1.mkdirs();
        }
        final File apkFile = new File(Data_FileDirPath + File.separator + mDownloadFileName);

        long range = 0;
        int progress = 0;
        if (apkFile.exists()) {
//            apkFile.delete();
            range = SPDownloadUtil.getInstance().get(downloadUrl, 0);
            progress = (int) (range * 100 / apkFile.length());
            if (range == apkFile.length()) {
                installApp(apkFile);
            }
            return;
        }

        Log.d(TAG, "range = " + range);

        final RemoteViews remoteViews = new RemoteViews(activity.getPackageName(), R.layout.layout_notifi);
        remoteViews.setProgressBar(R.id.progressBar, 100, progress, false);
        remoteViews.setTextViewText(R.id.textSpeed, progress + "%");
        DecimalFormat df = new DecimalFormat("#.##");
        remoteViews.setTextViewText(R.id.textSize, df.format(b2mbDouble(range)) + "");

        LinearLayout tuichudia = (LinearLayout) LayoutInflater.from(activity).inflate(R.layout.download_dialog, null);
        final AlertDialog.Builder abuilder = new AlertDialog.Builder(activity).setView(tuichudia);
        dialog = abuilder.create();
        /* dialog.getWindow().setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));*/
        dialog.show();
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                                        @Override
                                        public void onDismiss(DialogInterface dialog) {

                                        }
                                    }
        );
        is_bg = false;
        pb = (NumberProgressBar) tuichudia.findViewById(R.id.progress_bar_download_dialog);
        TextView lay_bg = (TextView) tuichudia.findViewById(R.id.lay_down_bg_dialog);
        pb.setProgress(progress);
        if (force) {
            lay_bg.setVisibility(View.GONE);
            dialog.setCancelable(false);
            dialog.setCanceledOnTouchOutside(false);
        } else
            lay_bg.setVisibility(View.VISIBLE);

        lay_bg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                is_bg = true;
                dialog.dismiss();

            }
        });


        mNotifyManager = (NotificationManager)
                activity.getSystemService(Context.NOTIFICATION_SERVICE);
        String channelId = "1";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel
                    (channelId, "Channel1", NotificationManager.IMPORTANCE_LOW);
            channel.enableLights(false); //是否在桌面icon右上角展示小红点   
            channel.setLightColor(Color.RED); //小红点颜色   
            channel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知 
            channel.enableVibration(false);
            mNotifyManager.createNotificationChannel(channel);
        }


        final NotificationCompat.Builder builder =
                new NotificationCompat.Builder(activity, channelId)
                        .setContent(remoteViews)
                        .setTicker("正在下载")
                        .setSmallIcon(R.drawable.logo);

        mNotification = builder.build();

        mNotifyManager.notify(downloadId, mNotification);

        final long frange = range;

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {

                DownloadAPi.Companion.downloadFile(frange, downloadUrl, mDownloadFileName, new DownloadCallBack() {
                    @Override
                    public void onPrepare(long size, String value) {
                        remoteViews.setTextViewText(R.id.textSize, FileUtil.getDataSize(size));

                    }

                    @Override
                    public void onProgress(final int progress) {
                        Log.e(TAG, "已下载" + progress + "%");
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                remoteViews.setProgressBar(R.id.progressBar, 100, progress, false);
                                remoteViews.setTextViewText(R.id.textSpeed, "已下载" + progress + "%");
                                Log.e(TAG, "已下载" + progress + "%");
                                mNotifyManager.notify(downloadId, mNotification);
                                if (progress == 100) {
                                    mNotifyManager.cancel(downloadId);
                                }
                                if (dialog != null && dialog.isShowing()) {
                                    pb.setProgress(progress);
                                }
                            }
                        });
//                        handler.post(new Runnable() {
//                            @Override
//                            public void run() {
//                                remoteViews.setProgressBar(R.id.progressBar, 100, progress, false);
//                                remoteViews.setTextViewText(R.id.textSpeed, "已下载" + progress + "%");
//                                Log.e(TAG, "已下载" + progress + "%");
//                                mNotifyManager.notify(downloadId, mNotification);
//                                if (progress == 100) {
//                                    mNotifyManager.cancel(downloadId);
//                                }
//                            }
//                        });


                    }

                    @Override
                    public void onCompleted() {
                        Log.d(TAG, "下载完成");
                        mNotifyManager.cancel(downloadId);
                        isLoading = false;
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (dialog != null && dialog.isShowing()) {
                                    pb.setProgress(100);
                                    dialog.dismiss();
                                }
                                installApp(apkFile);
                            }
                        });


                    }

                    @Override
                    public void onError(String msg) {
                        mNotifyManager.cancel(downloadId);
                        Log.d(TAG, "下载发生错误--" + msg);
                    }
                });

            }
        });
        thread.start();


    }

    public double b2mbDouble(long b) {
        return b * 1.0 / 1024 / 1024;
    }

    //安装apk
    protected void installApk(File file) {
        Intent intent = new Intent();
  /*      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context,
                    BuildConfig.APPLICATION_ID + ".fileProvider", file);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }*/

        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //执行的数据类型
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        activity.startActivity(intent);

    }

    private void installApp(File file) {
//        installApk(file);
        installApk(activity, file.getPath().toString());
    }

    public void installApk(Context context, String filePath) {
        try {
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            File file = new File(filePath);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // 7.0+以上版本
                Uri apkUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file); //与manifest中定义的provider中的authorities="cn.wlantv.kznk.fileprovider"保持一致
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            }
            context.startActivity(intent);
        } catch (IllegalArgumentException e) {

        }

    }


}
